package com.security.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.security.common.Result;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @作者: 林江
 * @创建时间: 2024/1/3
 * @功能: 认证成功或失败的处理方式
 */
public class CustomAuthenticationHandler implements AuthenticationSuccessHandler, AuthenticationFailureHandler {

    ObjectMapper objectMapper = new ObjectMapper();

    // 失败之后的处理
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(exception.getMessage()));

        // 另外一种，就是使用自定义Result
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication auth) throws IOException, ServletException {
        // TODO 可以再次生成token
        // 登录成功
        response.setContentType("application/json;charset=UTF-8");
        Result<Authentication> result = Result.success(auth);
        response.getWriter().println(objectMapper.writeValueAsString(result));
    }
}
